/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmListaLinea.java
 *
 * Created on 18/01/2012, 01:36:55 PM
 */

package Linea;

import Beans.LineaBean;
import Blogic.LineaBLogic;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author orellana
 */
public class frmListaLinea extends javax.swing.JFrame {

    // Atributos de la clase
    private String col[]={"Nombre", "Descripcion", "idLinea"};
    public DefaultTableModel modelLineas=new DefaultTableModel(col,0);
    private String lineaSel="";
    frmAltaLinea altaLinea=null;

    /** Creates new form frmListaLinea */
    public frmListaLinea() {
        initComponents();
        // Definimos posicion del formulario
        this.setLocationRelativeTo(null);
        // Definimos cerrado de formulario
        this.setDefaultCloseOperation(HIDE_ON_CLOSE);

        // Definimos el tamaño de las columnas (Tabla)
        getTablaListadoLinea();
        // Obtenemos linea
        obtLineas();
    }


    // Obtiene linea registradas
    public void obtLineas(){
    // Variables locales
    Vector datosLineas=new Vector();
    LineaBean sqlBean=new LineaBean();
    // Obtenemos la cantidad de registro de la tabla
    int count=modelLineas.getRowCount();
    // Hacemos el ciclo for para hacer la comparación
    for(int r=0; r<count;r++){
    // Eliminamos los datos que contenga la tabla
        modelLineas.removeRow(0);
    }
    // Realizamos la consulta
    datosLineas=(new LineaBLogic()).getDatosLineas(sqlBean);
    // Validamos registros encontrados
    if (!datosLineas.isEmpty()){
        // Vaciamos los datos en la tabla
        // Ciclo for
        for (int i=0; i<datosLineas.size();i++){
            LineaBean detalleDatosLinea=new LineaBean();
            detalleDatosLinea=(LineaBean) datosLineas.elementAt(i);
            // Vaciamos los datos
            modelLineas.addRow(new Object[]{detalleDatosLinea.getNombreLinea(), detalleDatosLinea.getDescripcionLinea(), detalleDatosLinea.getIdLinea()});
         }
      }else{
      modelLineas.addRow(new Object[]{"No existen Linea registradas"});
      }
    }

    //Limpiamos el modelo de la tabla
    private void deleteRowModelTable(){
      while(modelLineas.getRowCount()>0){
            modelLineas.removeRow(0);
        }
    }


     // Obtiene tamaño columnas tablas
    public void getTablaListadoLinea(){
        // Vaciamos el modelo con los datos
        tblListaLinea.setModel(modelLineas);
        // Definimos el tamaño de las columnas
        // Nombre linea
        tblListaLinea.getColumnModel().getColumn(0).setPreferredWidth(350);
        // Descripcion
        tblListaLinea.getColumnModel().getColumn(1).setPreferredWidth(200);
        // IdLinea
        tblListaLinea.getColumnModel().getColumn(2).setMinWidth(0);
        tblListaLinea.getColumnModel().getColumn(2).setMaxWidth(0);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        btnRegistrarLinea = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btnBuscar = new javax.swing.JButton();
        btnCerrar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblListaLinea = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sistemapegasso.SistemaPegassoApp.class).getContext().getResourceMap(frmListaLinea.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setName("jToolBar1"); // NOI18N

        btnRegistrarLinea.setIcon(resourceMap.getIcon("btnRegistrarLinea.icon")); // NOI18N
        btnRegistrarLinea.setText(resourceMap.getString("btnRegistrarLinea.text")); // NOI18N
        btnRegistrarLinea.setToolTipText(resourceMap.getString("btnRegistrarLinea.toolTipText")); // NOI18N
        btnRegistrarLinea.setFocusable(false);
        btnRegistrarLinea.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnRegistrarLinea.setName("btnRegistrarLinea"); // NOI18N
        btnRegistrarLinea.setPreferredSize(new java.awt.Dimension(36, 38));
        btnRegistrarLinea.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnRegistrarLinea.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRegistrarLineaActionPerformed(evt);
            }
        });
        jToolBar1.add(btnRegistrarLinea);

        btnModificar.setIcon(resourceMap.getIcon("btnModificar.icon")); // NOI18N
        btnModificar.setText(resourceMap.getString("btnModificar.text")); // NOI18N
        btnModificar.setToolTipText(resourceMap.getString("btnModificar.toolTipText")); // NOI18N
        btnModificar.setFocusable(false);
        btnModificar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnModificar.setName("btnModificar"); // NOI18N
        btnModificar.setPreferredSize(new java.awt.Dimension(36, 38));
        btnModificar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnModificar);

        btnEliminar.setIcon(resourceMap.getIcon("btnEliminar.icon")); // NOI18N
        btnEliminar.setText(resourceMap.getString("btnEliminar.text")); // NOI18N
        btnEliminar.setToolTipText(resourceMap.getString("btnEliminar.toolTipText")); // NOI18N
        btnEliminar.setFocusable(false);
        btnEliminar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEliminar.setName("btnEliminar"); // NOI18N
        btnEliminar.setPreferredSize(new java.awt.Dimension(36, 38));
        btnEliminar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnEliminar);

        btnBuscar.setIcon(resourceMap.getIcon("btnBuscar.icon")); // NOI18N
        btnBuscar.setText(resourceMap.getString("btnBuscar.text")); // NOI18N
        btnBuscar.setToolTipText(resourceMap.getString("btnBuscar.toolTipText")); // NOI18N
        btnBuscar.setName("btnBuscar"); // NOI18N
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnBuscar);

        btnCerrar.setIcon(resourceMap.getIcon("btnCerrar.icon")); // NOI18N
        btnCerrar.setText(resourceMap.getString("btnCerrar.text")); // NOI18N
        btnCerrar.setToolTipText(resourceMap.getString("btnCerrar.toolTipText")); // NOI18N
        btnCerrar.setFocusable(false);
        btnCerrar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnCerrar.setName("btnCerrar"); // NOI18N
        btnCerrar.setPreferredSize(new java.awt.Dimension(36, 38));
        btnCerrar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnCerrar);

        jLabel1.setBackground(resourceMap.getColor("jLabel1.background")); // NOI18N
        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setForeground(resourceMap.getColor("jLabel1.foreground")); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N
        jLabel1.setOpaque(true);

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        txtNombre.setFont(resourceMap.getFont("txtNombre.font")); // NOI18N
        txtNombre.setText(resourceMap.getString("txtNombre.text")); // NOI18N
        txtNombre.setName("txtNombre"); // NOI18N
        txtNombre.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                txtNombreMousePressed(evt);
            }
        });
        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtNombreKeyPressed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tblListaLinea.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Nombre", "Descripción"
            }
        ));
        tblListaLinea.setName("tblListaLinea"); // NOI18N
        tblListaLinea.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblListaLineaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblListaLinea);
        tblListaLinea.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tblListaLinea.columnModel.title0")); // NOI18N
        tblListaLinea.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("tblListaLinea.columnModel.title1")); // NOI18N

        jLabel3.setBackground(resourceMap.getColor("jLabel3.background")); // NOI18N
        jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
        jLabel3.setForeground(resourceMap.getColor("jLabel3.foreground")); // NOI18N
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N
        jLabel3.setOpaque(true);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 597, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 441, Short.MAX_VALUE)
                .addGap(83, 83, 83))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 573, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 597, Short.MAX_VALUE)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 597, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnRegistrarLineaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrarLineaActionPerformed
        // TODO add your handling code here:
        // Cargamos el formulario de alta de linea
    
        altaLinea=new frmAltaLinea(1);
        // Cachamos la accion del boton guardar
        altaLinea.btnGuardar.setActionCommand("nuevaAltaLinea");
        altaLinea.btnGuardar.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if(e.getActionCommand().equals("nuevaAltaLinea")){
                altaLinea.altaClickLinea();
                obtLineas();
                }
            }
        });
        // Mostramos el formulario
        altaLinea.setVisible(true);
    }//GEN-LAST:event_btnRegistrarLineaActionPerformed

    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
        // TODO add your handling code here:
        // Evaluamos si selecciono algun proveedor a modificar
        if(!lineaSel.equalsIgnoreCase("")){
        // Cargamos el formulario de modificar linea
        final frmAltaLinea modificarLinea=new frmAltaLinea(2);
        // Mostramos el formulario
        modificarLinea.setVisible(true);
        // Cambiamos titulo de la ventana
        modificarLinea.setTitle("Modificar Linea");

        // Seteamos los Datos
        modificarLinea.setIdLinea(modelLineas.getValueAt(Integer.parseInt(lineaSel.toString()),2).toString());
        //System.out.println("imprime"+ modelCategorias.getValueAt(Integer.parseInt(categoriaSel.toString()),2).toString());
        // Obtenemos los Datos del Cliente
        modificarLinea.obtDatosLinea();

        // Cambiamos el Valor del registro Seleccionado
        lineaSel="";
        //Mostramos la ventana modificar linea
        modificarLinea.setVisible(true);

        modificarLinea.btnGuardar.setActionCommand("nuevaAltaLinea");
        modificarLinea.btnGuardar.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
               if (e.getActionCommand().equals("nuevaAltaLinea")){
               modificarLinea.altaClickLinea();
               obtLineas();
               }
            }
        });

        }else{
        // Mensaje al usuario
            JOptionPane.showMessageDialog(null,"Debe Seleccionar una Linea de Producto a Modificar, Verifique...","Categorias",JOptionPane.WARNING_MESSAGE);
        }

    }//GEN-LAST:event_btnModificarActionPerformed

    private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed
        // TODO add your handling code here:
        // Cerramos el formulario
        this.setVisible(false);
    }//GEN-LAST:event_btnCerrarActionPerformed

    private void tblListaLineaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblListaLineaMouseClicked
        // TODO add your handling code here:
        this.lineaSel=Integer.toString(tblListaLinea.getSelectedRow());
    }//GEN-LAST:event_tblListaLineaMouseClicked
    
    
    //Evento de eliminacion de registro
    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        //Asignamos variables locales
        LineaBean sqlLineaBean=new LineaBean();
        Vector eliminarLinea=new Vector();
        //Eliminamos la linea seleccionada
        //Verificamos que se haya seleccionado un registro de la tabla
        if(!lineaSel.equalsIgnoreCase("")){
             //Seteamos los datos
            sqlLineaBean.setIdLinea(modelLineas.getValueAt(Integer.parseInt(lineaSel.toString()), 2).toString());
            //Eliminamos lineanea
            eliminarLinea=(new LineaBLogic()).deleteDatosLinea(sqlLineaBean);
            //Evaluamos respuesta
            if(eliminarLinea.elementAt(0).toString().equalsIgnoreCase("OK")){
            lineaSel="";
            // Mensaje al Usuario
                JOptionPane.showMessageDialog(null,"Linea Eliminado Satisfactoriamente","Eliminar",JOptionPane.INFORMATION_MESSAGE);
                obtLineas();
                System.out.println("entro aka de eliminacion");
            }else{
                // Mensaje al Usuario
                JOptionPane.showMessageDialog(null,"Ocurrio un Error al Momento de Eliminar lineas","Eliminar",JOptionPane.ERROR_MESSAGE);
            }
        }else{
            // Mensaje al Usuario
            JOptionPane.showMessageDialog(null,"Debe Seleccionar un Registro a Eliminar, Verifique","Eliminar",JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_btnEliminarActionPerformed

    private void txtNombreMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtNombreMousePressed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNombreMousePressed

    private void txtNombreKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyPressed
        // TODO add your handling code here:
         System.out.println("entre akii");
        LineaBean buscarLinea = new LineaBean();
        Vector lineaVector = new Vector();
        LineaBLogic lineaBlogic= new LineaBLogic();
        buscarLinea.setNombreLinea(txtNombre.getText().toString().trim());

        lineaVector=lineaBlogic.buscarDatosLineaActivo(buscarLinea);
        if(lineaVector.size()>0){
           deleteRowModelTable();
           for(int i=0; i<lineaVector.size();i++){
               buscarLinea=(LineaBean) lineaVector.elementAt(i);
           modelLineas.addRow(new Object[]{buscarLinea.getNombreLinea(), buscarLinea.getDescripcionLinea(),buscarLinea.getIdLinea()});
        }
        }
    }//GEN-LAST:event_txtNombreKeyPressed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        // TODO add your handling code here:
          // Variables locales
        LineaBean sqlBean=new LineaBean();
        Vector datosLineaActivo= new Vector();
        LineaBean lineaActivo= new LineaBean();
System.out.println("Entre akiiii buscar");
        //Realizamos la busqueda de la categoria
        //Seteamos los datos
        sqlBean.setNombreLinea(txtNombre.getText());
        datosLineaActivo=(new LineaBLogic().buscarDatosLineaActivo(sqlBean));
        //Limpiamos la tabla
        deleteRowModelTable();
        //Evaluamos resultado obtenido
        if(datosLineaActivo.size()!=0){
        //Agregamos los datos al modelo
            for(int i=0; i<datosLineaActivo.size();i++){
                //Vaciamos los datos
                //CategoriaBean categoriaActivos = new CategoriaBean();
            lineaActivo=(LineaBean) datosLineaActivo.elementAt(i);
            //Agregamos los datos al modelo de la tabla
            modelLineas.addRow(new Object[]{lineaActivo.getNombreLinea(),lineaActivo.getDescripcionLinea(),lineaActivo.getIdLinea()});
        //System.out.println("imprime categorias "+modelCategorias);
            }
        }else{
        //No existen registros
            //modelCategorias.addRow(new Object[]{"No existen categorias registradas"});

        }
    }//GEN-LAST:event_btnBuscarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmListaLinea().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCerrar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnModificar;
    private javax.swing.JButton btnRegistrarLinea;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTable tblListaLinea;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables

}
